<template>
  <div class="page-container">
    <div class="page-header">
      <div class="page-tile">
        <el-button class="icon-button back-button" style="margin-right: 10px;" @click="$router.back()">
          <i class="el-icon-arrow-left" style="font-size: 12px"></i>
        </el-button>
        <span style="display:flex">
          <link-button :content="$t('route.resource')" @click="$router.push({ name: 'ResourcePool' })" />&nbsp;/&nbsp;{{poolData.name}}
        </span>
        <i v-if="false" class="iconfont iconzhongyiicon_gaojing"></i>
      </div>
      <div class="left-wrapper"></div>
      <div class="right-wrapper"></div>
    </div>
    <el-scrollbar class="page-content">
      <div class="content-wrapper">
        <el-card class="content-info" v-loading="loading">
          <el-form :inline="true" class="" style="margin-bottom: 20px;">
            <el-form-item :label="$t('resource.Horizon')">
              {{ poolData.horizon_resources }}
            </el-form-item>
            <el-form-item :label="$t('resource.Daas')">
              {{ poolData.daas_resources }}
            </el-form-item>
            <!-- <el-form-item :label="$t('common.desktop')">
              {{ poolData.daas_resource_count }}
            </el-form-item> -->
          </el-form>
          <el-form :inline="true" class="">
            <el-form-item :label="$t('common.description')">
              {{ poolData.description }}
            </el-form-item>
          </el-form>
        </el-card>
        <el-card>
          <el-tabs v-model="currentDetail" @tab-click="changeDetail">
            <el-tab-pane :label="$t('resource.Horizon')" name="Horizon"></el-tab-pane>
            <el-tab-pane :label="$t('resource.Daas')" name="Daas"></el-tab-pane>
          </el-tabs>
          <basic-table
            ref="BasicTable"
            :pageMethod="(params) => {
              params.pool_id = poolData.id;
              if (tableSearch) {
                      params.page = 1;
                      tableSearch = false;
                    }
              if (currentDetail === 'Horizon') {
                params.search = horizonSearchValue;
                return $pandaApi.apiGetHorizonTenantList(params);
              } else if (currentDetail === 'Daas') {
                params.search = daasSearchValue;
                return $pandaApi.apiGetDaaSTenantList(params);
              }
            }"
            :afterPageMethod="afterPageMethod"
          >
            <template #table-options="tableSlotData">
              <div class="table-left-options">
                <el-button type="primary" class="icon-button setting-button" style="width: auto;" @click="() => {
                  if (currentDetail === 'Horizon') {
                    $refs.HorizonFormDialop.init('create',poolData.id);
                  } else if (currentDetail === 'Daas') {
                    $refs.DaasFormDialop.init('create', poolData.id);
                  }
                }">
                  <i class="iconfont iconzhongyiicon_chuangjian" style="font-size: 12px; margin-right: 5px;"></i>
                  <span style="font-size: 12px;">{{$t('common.Create')}}</span>
                </el-button>
                <el-button class="icon-button setting-button" style="width: auto; margin-left: 10px;" @click="batchDelete(tableSlotData.table.selectRows)" :disabled="tableSlotData.table.selectRows.length <= 0">
                  <i class="el-icon-delete" style="font-size: 12px; margin-right: 5px;"></i>
                  <span style="font-size: 12px;">{{ $t('common.BatchDelete') }}</span>
                </el-button>
              </div>
              <div class="table-right-options">
                <el-input v-if="currentDetail === 'Horizon'" @keyup.enter.native="tableSearchChange(tableSlotData)" :placeholder="$t('common.SearchByName')" style="width:200px" v-model="horizonSearchValue" >
                </el-input>
                <el-button v-if="currentDetail === 'Horizon'" @click="tableSearchChange(tableSlotData)" type="primary" style="margin-left: 10px;" >{{ $t('common.search') }}</el-button>
                <el-input v-if="currentDetail === 'Daas'" @keyup.enter.native="tableSearchChange(tableSlotData)" :placeholder="$t('common.SearchByName')" style="width:200px" v-model="daasSearchValue" >
                </el-input>
                <el-button v-if="currentDetail === 'Daas'" @click="tableSearchChange(tableSlotData)" type="primary" style="margin-left: 10px;" >{{ $t('common.search') }}</el-button>
              </div>
            </template>
            <template #table-column="tableSlotData">
              <el-table-column type="selection" width="40" align="center"></el-table-column>
              <el-table-column
                prop="name"
                :label="$t('common.name')"
              >
                <template #default="props">
                  <div class="cloudtips">
                    <span>{{props.row.name}}</span>
                    <div class="cloudtips__block">
                      <el-tooltip effect="dark" placement="right">
                        <div slot="content">
                          <!-- <div
                            v-if="props.row.sync_info.sync_panda_status || props.row.sync_info.sync_tunny_status"
                            class="errrormessgae"
                          >
                            <span>{{ $t('othermessages.' + (props.row.sync_info.sync_panda_status || props.row.sync_info.sync_tunny_status)) }}</span><br>
                          </div> -->
                          <div
                            v-if="props.row.sync_resource_res.sync_desktop_res && props.row.sync_resource_res.sync_desktop_res != 2010"
                            class="errrormessgae"
                          >
                            <span>{{ $t('resourceError.' + (props.row.sync_resource_res.sync_desktop_res)) }}</span>
                          </div>
                          <div
                            v-if="props.row.sync_resource_res.sync_ad_user_res && props.row.sync_resource_res.sync_ad_user_res != 2010"
                            class="errrormessgae"
                          >
                            <span>{{ $t('resourceError.' + (props.row.sync_resource_res.sync_ad_user_res)) }}</span>
                          </div>
                          <div
                            v-if="props.row.sync_resource_res.sync_desktop_res === 2010 && props.row.sync_resource_res.sync_ad_user_res === 2010"
                            class="errrormessgae"
                          >
                            <span>{{ $t('resourceError.' + (props.row.sync_resource_res.sync_ad_user_res)) }}</span>
                          </div>
                        </div>
                        <span>
                          <i
                            class="el-icon-warning-outline"
                            style="color:#FF931D;font-size:14px;"
                            v-show="!(syncRunning(props) || syncSuccessful(props) || nonSync(props))"
                          >
                          </i>
                          <i
                            class="el-icon-circle-check"
                            style="color:#10C038;font-size:14px;"
                            v-show="syncSuccessful(props)"
                          >
                          </i>
                        </span>
                      </el-tooltip>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                v-if="currentDetail !== 'Daas'"
                prop="availability_zone"
                :label="$t('desktopManage.availabilityZone')"
              >
              </el-table-column>
              <el-table-column
                v-if="currentDetail === 'Daas'"
                :label="$t('common.belongTenant')"
                prop="cloud_tenant_name">
              </el-table-column>
              <el-table-column
                prop="uri"
                :label="$t('common.manageAddress')">
                <template #default="props">
                  <span>{{props.row.uri + '/admin'}}</span>
                  <!-- <el-link :href="props.row.uri + '/admin'" type="primary" :underline="false" target="_blank" style="font-size:12px">{{props.row.uri}}</el-link> -->
                </template>
                <!-- <template #default="props">
                  <link-button :content="props.row.uri" :size="10" :font-size="'12px'" @click="() => {
                    window.open(props.row.uri + '/admin');
                  }" />
                </template> -->
              </el-table-column>
              <el-table-column
                prop="ad_info.server_uri"
                :label="$t('common.adAddress')">
              </el-table-column>
              <el-table-column
                prop="connection_info.gateway"
                :label="$t('common.gatewayAddress')">
                <template #default="props">
                  <div class="cloudtips">
                    <el-link :href="props.row.connection_info.gateway" type="primary" :underline="false" target="_blank" style="font-size:12px">{{props.row.connection_info.gateway}}</el-link>
                    <div class="cloudtips__block">
                      <el-tooltip effect="dark" :content="$t('resource.cloudLineTips')" placement="right" v-if="currentDetail == 'Daas'">
                        <i class="iconfont iconyun1"
                          style="color:#10C038;"
                          v-show="props.row.dedicated_line_gateway_address !== ''"></i>
                      </el-tooltip>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="desktop_pools"
                width="100"
                :label="$t('common.desktopPool')">
              </el-table-column>
              <el-table-column
                prop="desktops"
                width="100"
                :label="$t('common.desktop')">
              </el-table-column>
              <el-table-column
                :label="$t('common.action')"
                width="160"
              >
                <template #default="props">
                  <link-button :content="$t('common.edit')" :size="10" :font-size="'12px'" @click="() => {
                    const formData = {
                      id: props.row.id,
                      name: props.row.name,
                      availability_zone: props.row.availability_zone,
                      platform_uuid: props.row.platform_uuid,
                      manage_address: props.row.uri,
                      manage_account: props.row.credential.username,
                      manage_password: props.row.credential.password,
                      desktop_getaway_address: props.row.connection_info.gateway,
                      cloud_line: props.row.dedicated_line_gateway_address,
                      tenant: props.row.cloud_tenant_name,
                      ad_adress: props.row.ad_info.server_uri,
                      ad_account: props.row.ad_info.bind_dn,
                      ad_password: props.row.ad_info.bind_password,
                      ad_dn: props.row.ad_info.search_base_dn,
                      ad_filiter: props.row.ad_info.search_filter,
                      api_proxy: props.row.api_proxy
                    };
                    if (currentDetail === 'Horizon') {
                      $refs.HorizonFormDialop.init('edit', poolData.id, formData)
                    } else if (currentDetail === 'Daas') {
                      $refs.DaasFormDialop.init('edit', poolData.id, formData)
                    }
                  }" style="margin-right: 15px;" />
                  <link-button :content="$t('common.delete')" :size="10" :font-size="'12px'" @click="deleteRow(props.row)" />
                  <el-dropdown style="margin-left: 10px;cursor: pointer;" :hide-on-click="false" @command="(cmd) => {
                    switch(cmd) {
                      case 'management-desktop':
                        goToDesktopPools(props.row)
                        break;
                      case 'synchronize-now':
                        synchronizeNowLoading = true;
                        if (currentDetail === 'Horizon') {
                          $pandaApi.syncHorizonDesktopPools(props.row.resource_pool, props.row.id).then(() => {
                            tableSlotData.table.refresh();
                            $message({
                              message: $t('desktopManage.message.startSync').toString(),
                              type: 'success'
                            });
                          }).catch((error) => {
                            $message({
                              message: $t('desktopManage.message.syncFail').toString(),
                              type: 'warning'
                            });
                          }).finally(() => {
                            synchronizeNowLoading = false;
                          });
                        } else {
                          $pandaApi.syncDaaSDesktopPools(props.row.resource_pool, props.row.id).then(() => {
                            tableSlotData.table.refresh();
                            $message({
                              message: $t('desktopManage.message.startSync').toString(),
                              type: 'success'
                            });
                          }).catch((error) => {
                            $message({
                              message: $t('desktopManage.message.syncFail').toString(),
                              type: 'warning'
                            });
                          }).finally(() => {
                            synchronizeNowLoading = false;
                          });
                        }
                    }
                  }">
                    <span class="el-dropdown-link">
                      {{$t('common.More')}}<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item :command="'management-desktop'">{{ $t('resource.managementDesktopPools') }}</el-dropdown-item>
                      <el-dropdown-item :disabled="synchronizeNowLoading" :command="'synchronize-now'">{{ $t('resource.synchronizeNow') }}<i v-if="synchronizeNowLoading" class="el-icon-loading" style="color: #333333; margin-left: 5px;"></i></el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </el-table-column>
            </template>
            <template #others-elements="tableSlotData">
              <horizon-form-dialop ref="HorizonFormDialop" :submit-method="(data) => {
                switch(data.type) {
                  case 'create':
                    return $pandaApi.apiPostHorizonTenantList(data).then((res) => {
                      tenantDuplicatename('Horizon', 'create', res);
                    }).catch((err) => {
                      tenantDuplicatename('Horizon', 'create', err);
                    });
                    break;
                  case 'edit':
                    return $pandaApi.apiPutHorizonTenantList(data).then((res) => {
                      tenantDuplicatename('Horizon', 'edit', res);
                    }).catch((err) => {
                      tenantDuplicatename('Horizon', 'edit', err);
                    });;
                }
              }" />
              <daas-form-dialop ref="DaasFormDialop" :submit-method="(data) => {
                switch(data.type) {
                  case 'create':
                    return $pandaApi.apiPostDaasTenantList(data).then((res) => {
                      tenantDuplicatename('DaaS', 'create', res);
                    }).catch((err) => {
                      tenantDuplicatename('DaaS', 'create', err);
                    });;
                    break;
                  case 'edit':
                    return $pandaApi.apiPutDaasTenantList(data).then((res) => {
                      tenantDuplicatename('DaaS', 'edit', res);
                    }).catch((err) => {
                      tenantDuplicatename('DaaS', 'edit', err);
                    });;
                }
                
              }" />
              <password-delete-dialog ref="PasswordDeleteDialog" :delete-method="(resourceList, meta) => {
                if (meta.type === 'Horizon') {
                  return $pandaApi.apiBatchDeleteHorizonResourcePools(meta.pool_id ,resourceList).then(() => {
                    $message({
                      message: $t('desktopManage.message.operationSuccess', {operation: $t('resource.deleteTenant')}).toString(),
                      type: 'success'
                    });
                    tableSlotData.table.deleteRefresh(resourceList.length);
                  });
                } else if (meta.type === 'Daas') {
                  return $pandaApi.apiBatchDeleteDaasResourcePools(meta.pool_id, resourceList).then(() => {
                    $message({
                      message: $t('desktopManage.message.operationSuccess', {operation: $t('resource.deleteTenant')}).toString(),
                      type: 'success'
                    });
                    tableSlotData.table.deleteRefresh(resourceList.length);
                  });
                }
              }" />
            </template>
          </basic-table>
        </el-card>
      </div>
    </el-scrollbar>
  </div>
</template>
<script lang="ts">
import Vue from 'vue'
import BasicTable from '../../components/Basic/Table/BasicTable.vue';
import LinkButton from '../../components/Basic/Button/LinkButton.vue';
import HorizonFormDialop from './components/HorizonFormDialop.vue';
import DaasFormDialop from './components/DaasFormDialop.vue';
import PasswordDeleteDialog from './components/PasswordDeleteDialog.vue';
export default Vue.extend({
  components: {
    BasicTable,
    LinkButton,
    HorizonFormDialop,
    DaasFormDialop,
    PasswordDeleteDialog
  },
  computed: {
    window: () => window
  },
  data() {
    return {
      loading: false,
      poolData: {},
      currentDetail: "Horizon",
      horizonSearchValue: "",
      daasSearchValue: "",
      synchronizeNowLoading: false,
      tableSearch: false,
      syncingArray: []
    }
  },
  watch: {
    currentDetail(newVal: any) {
      localStorage.setItem('currentDetail', newVal);
    }
  },
  created() {
    if (localStorage.getItem('currentDetail')) {
      (this as any).currentDetail = localStorage.getItem('currentDetail');
    }
    if ((this as any).$route.query && (this as any).$route.query.poolid) {
      (this as any).poolData.id = (this as any).$route.query.poolid;
      (this as any).loading = true;
      (this as any).$pandaApi.apiGetResourceInfo((this as any).$route.query.poolid).then((res: any) => {
        this.loading = false;
        (this as any).poolData = res;
      });
    } else {
      (this as any).$router.back();
    }
  },
  mounted(){
    const poolId = (this as any).$route.query.poolid;
    (window as any).poolDetailIntervalor ? clearInterval((window as any).poolDetailIntervalor) : "";
    (window as any).poolDetailIntervalor = setInterval(() => {
      if (this.syncingArray.length > 0) {
        let apiName = "apiGetHorizonTenantList";
        if (this.currentDetail === 'Daas') {
          apiName = "apiGetDaaSTenantList";
        }
        this.$pandaApi[apiName]({
          pool_id: poolId,
          ids: this.syncingArray.map((row: any) => row.id).join(",")
        }).then((pollingRes: any) => {
          const runningArray: Array<any> = [];
          pollingRes.forEach((result: any) => {
            if (result.sync_resource_res.sync_desktop_res === 3000 || result.sync_resource_res.sync_ad_user_res === 3000) {
              runningArray.push(result);
            } else {
              const index = (this.$refs["BasicTable"] as any).tableData.findIndex((data: any) => data.id === result.id);
              (this.$refs["BasicTable"] as any).updateRow({ index, row: result });
            }
          });
          (this.syncingArray as Array<any>) = runningArray;
        });
      }
    }, 10_000);
  },
  methods: {
    // 页面刷新重置page
    tableSearchChange(table: any) {
      (this as any).tableSearch = true;
      table.table.refresh(true);
    },
    //管理桌面池
    goToDesktopPools(row: any) {
      // console.log(row);
      if (row.resource_type === 'HorizonView') {
        localStorage.setItem('Horizon_resource_value_system',row.resource_pool);
        localStorage.setItem('Horizon_tenant_value_system', row.id);
        (this as any).$router.push({path: '/desktopManage/HorizonDesktopPools'})
      } else {
        localStorage.setItem('resource_value_system',row.resource_pool);
        localStorage.setItem('tenant_value_system', row.id);
        (this as any).$router.push({path: '/desktopManage/DaaSDesktopPools'})
      }
    },
    changeDetail(tab: any) {
      (this as any).currentDetail = tab.name;
      (this as any).$nextTick(() => {
        (this as any).tableSearch = true;
        (this as any).$refs.BasicTable.refresh();
      });
    },
    batchDelete(selectRows: Array<any>) {
      if ((this as any).currentDetail === 'Horizon') {
        (this as any).$refs.PasswordDeleteDialog.init({
          meta: {
            type: "Horizon",
            pool_id: (this as any).poolData.id
          },
          title: (this as any).$t('resource.BatchDeleteHorizonTitle'),
          tip: (this as any).$t('resource.batchDeleteHorizonTip'),
          message: (this as any).$t('resource.batchDeleteHorizonMessage'),
          resourceList: selectRows
        });
      } else if ((this as any).currentDetail === 'Daas') {
        (this as any).$refs.PasswordDeleteDialog.init({
          meta: {
            type: "Daas",
            pool_id: (this as any).poolData.id
          },
          title: (this as any).$t('resource.BatchDeleteDaasTitle'),
          tip: (this as any).$t('resource.batchDeleteDaasTip'),
          message: (this as any).$t('resource.batchDeleteDaasMessage'),
          resourceList: selectRows
        });
      }
    },
    deleteRow(row: any) {
      if ((this as any).currentDetail === 'Horizon') {
        (this as any).$refs.PasswordDeleteDialog.init({
          meta: {
            type: "Horizon",
            pool_id: (this as any).poolData.id
          },
          title: (this as any).$t('resource.DeleteHorizonTitle', row),
          tip: (this as any).$t('resource.deleteHorizonTip', row),
          message: (this as any).$t('resource.deleteHorizonMessage', row),
          resourceList: [row]
        });
      } else if ((this as any).currentDetail === 'Daas') {
        (this as any).$refs.PasswordDeleteDialog.init({
          meta: {
            type: "Daas",
            pool_id: (this as any).poolData.id
          },
          title: (this as any).$t('resource.DeleteDaasTitle', row),
          tip: (this as any).$t('resource.deleteDaasTip', row),
          message: (this as any).$t('resource.deleteDaasMessage', row),
          resourceList: [row]
        });
      }
    },
    tenantDuplicatename(type: any, operationType: any, error: any) {
      if (type === 'Horizon') {
        if (error.error && error.msg.name && error.msg.name[0] && error.msg.name[0] == "具有 name 的 st resource 已存在。") {
          (this as any).$message({
            message: (this as any).$t('resource.tenantNameExists').toString(),
            type: 'warning'
          });
        } else {
          (this as any).$refs.HorizonFormDialop.handleClose();
          (this as any).$message({
            message: (this as any).$t('desktopManage.message.operationSuccess', {operation: operationType === 'create' ? (this as any). $t('resource.createHorizon') :  (this as any). $t('resource.editHorizon')}).toString(),
            type: 'success'
          });
          (this as any).$refs.BasicTable.refresh();
        }
      } else {
        if (error.error && error.msg.name && error.msg.name[0] == "具有 name 的 mt resource 已存在。") {
          (this as any).$message({
            message: (this as any).$t('resource.tenantNameExists').toString(),
            type: 'warning'
          });
        } else if (error.error && error.msg.message == 'the daas resource has been occupied by other cloud tenant') {
          (this as any).$message({
            message: (this as any).$t('resource.tenantDaasExists').toString(),
            type: 'warning'
          });
        } else {
          (this as any).$refs.DaasFormDialop.handleClose();
          (this as any).$message({
            message: (this as any).$t('desktopManage.message.operationSuccess', {operation: operationType === 'create' ? (this as any). $t('resource.createDaaS') :  (this as any). $t('resource.editDaaS')}).toString(),
            type: 'success'
          });
          (this as any).$refs.BasicTable.refresh();
        }
      }
    },
    afterPageMethod(res: any) {
      const runningArray: Array<any> = [];
      res.rows.forEach((row: any, index: number) => {
        if (row.sync_resource_res.sync_desktop_res === 3000 || row.sync_resource_res.sync_ad_user_res === 3000) {
          runningArray.push(row);
        }
      });
      (this.syncingArray as Array<any>) = runningArray;
    },
    // 同步中
    syncRunning(props: any) {
      return props.row.sync_resource_res.sync_ad_user_res == 3000 || props.row.sync_resource_res.sync_desktop_res == 3000;
    },
    // 同步成功
    syncSuccessful(props: any) {
      return props.row.sync_resource_res.sync_ad_user_res == 2010 && props.row.sync_resource_res.sync_desktop_res == 2010;
    },
    // 没有同步信息
    nonSync(props: any) {
      return !props.row.sync_resource_res.sync_ad_user_res && !props.row.sync_resource_res.sync_desktop_res;
    },
  }
})
</script>
<style lang="scss" scoped>
.page-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #EFF1F4;

  .page-header {
    height: 60px;
    background-color: #FFFFFF;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #D9D9D9;

    .page-tile {
      color: #031129;
      font-size: 16px;
      margin-left: 20px;
      display: flex;
      align-items: center;

      .back-button {
        width: 24px;
        height: 24px;
        padding: 0px 6px;
      }

      .iconzhongyiicon_gaojing {
        margin-left: 5px;
        font-size: 18px !important;
      }
    }
  }

  .page-content {
    height: calc(100vh - 110px);
    overflow: hidden;
    flex-grow: 1;

    .content-wrapper {
      padding: 15px;

      .content-info {
        margin-bottom: 20px;

        ::v-deep .el-form-item {
          margin-bottom: 0px;
          margin-right: 40px
        }

        ::v-deep .el-form-item__label, ::v-deep .el-form-item__content {
          color: #999999;
          font-size: 12px;
        }

        ::v-deep .el-form-item__content {
          color: #333333;
        }
      }
    }
  }
}

.table-left-options {
  display: flex;
}

.table-right-options {
  display: flex;

  .setting-button {
    margin-right: 10px;
  }
}
.cloudtips {
  display: flex;
  justify-content: flex-start;

 
  &__block{
    position: relative;
    height: 16px;
    width: 16px;
    margin-left:6px;
 
  }
}
.errrormessgae{
  margin-bottom: 5px;
}

.iconyun1::before {
  height: 18px;
  line-height: 18px;
  font-size: 18px;
}
</style>
